package com.tencent.wxcloudrun.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
@Slf4j
public class RedisLockAspect {

    @Resource
    private RedissonLockService redissonLockService;

    /**
     * 在被标注的方法的入参中寻找叫 openId 的值，如果没有找到，就用前缀作为锁的key，找到了就将其拼接到后面之后，作为锁的key。
     */
    @Around("@annotation(redisLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {
        String lockKeyPrefix = redisLock.prefix();
        int waitTime = redisLock.waitTime();
        long expire = redisLock.expire();
        String lockKey = lockKeyPrefix + "_" + UserContext.getOpenId();
        log.info(">>>>>> 切面日志，准备上锁。");
        boolean isLocked = redissonLockService.lock(lockKey, waitTime, expire);
        try {
            if (!isLocked) {
                throw new CustomException("上锁失败！");
            }
            return joinPoint.proceed();
        } finally {
            redissonLockService.unlock(lockKey);
            log.info(">>>>>> 切面日志，解锁完成。");
        }
    }
}



